package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.RoleAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.databinding.FragmentHouseInfoBinding;
import com.jinlejia.erp.ui.common.ImageViewPagerActivity;
import com.jinlejia.erp.ui.common.WebViewActivity;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DateUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;


public class HouseInfoFragment extends Fragment {


    RoleAdapter roleAdapter;
    ArrayList<Map<String, Object>> dataList = new ArrayList<>();

    private String rCode;
    private String type;
    private String phoneNO;
    private String finalVRStationLink;

    private FragmentHouseInfoBinding binding;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_house_info, null);
        binding = DataBindingUtil.bind(view);
        binding.rlVisit.setOnClickListener(this::onClick);
        binding.rlAdjustLayout.setOnClickListener(this::onClick);
        binding.vrBtn.setOnClickListener(this::onClick);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.bind(view);

        binding.rlVisit.setOnClickListener(this::onClick);
        binding.rlAdjustLayout.setOnClickListener(this::onClick);

        roleAdapter = new RoleAdapter(getActivity(), dataList);
        binding.yfListview.setAdapter(roleAdapter);

        String isDuty = getActivity().getIntent().getStringExtra("isDuty");


        //责字是否显示
        if (!isDuty.equals("null")){
            if (Integer.parseInt(isDuty)==0){
                binding.tvIsDuty.setVisibility(View.GONE);
            }else{
                binding.tvIsDuty.setVisibility(View.VISIBLE);
            }
        }

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_visit:
                //带访记录
                Intent intent = new Intent(getActivity(), VisitRecordActivity.class);
                intent.putExtra("code", rCode);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.rl_adjust_layout:
                //调价记录
                Intent intent1 = new Intent(getActivity(), AdjustmentRecordActivity.class);
                intent1.putExtra("code", rCode);
                intent1.putExtra("type", type);
                startActivity(intent1);
                break;

            case R.id.vr_btn:
                Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
                intent2.putExtra("url", finalVRStationLink);
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    @Subscriber(tag = "TAG_SHS_DATA")
    public void shsData(JSONObject data) {
        type = "shs";
        binding.price.setText(data.get("salePrice") + "万");
        binding.averagePrice.setText("均价:".concat(data.get("unitPrice").toString()).concat("元/㎡"));
        parseData(data);
    }

    @Subscriber(tag = "TAG_RENT_DATA")
    public void rentData(JSONObject data) {
        type = "rent";
        binding.price.setText(data.get("salePrice") + "元/月");
        parseData(data);
    }

    private void parseData(JSONObject data) {
        //VR房源
        String VRImgUrl = "", VRStationLink = "";
        if (data.containsKey("vrshsResult") || data.containsKey("vrrentResult")) {
            binding.vrBtn.setVisibility(View.VISIBLE);
            binding.vrBtn.getBackground().mutate().setAlpha(200);
            JSONObject vrObject;
            if (data.containsKey("vrshsResult")) {
                vrObject = data.getJSONObject("vrshsResult");
            } else {
                vrObject = data.getJSONObject("vrrentResult");
            }
            if (vrObject.getIntValue("sceneType") == 1) {
                VRImgUrl = ApiConfig.MAGEHEADER_URL() + vrObject.getString("vrimgUrl");
                VRStationLink = vrObject.getString("vrstationLink");
            }
        }
        final String finalVRImgUrl = VRImgUrl;
        finalVRStationLink = VRStationLink;


        //房源状态
        if (data.containsKey("state")){
            switch (Integer.parseInt((String) data.get("state"))){

                case 0:
                    binding.tvHouseStatus.setText("待发布");
                    break;

                case 1:
                    binding.tvHouseStatus.setText("待确认");
                    break;

                case 2:
                    binding.tvHouseStatus.setText("有效");
                    break;
                case 6:
                    binding.tvHouseStatus.setText("驳回");
                    break;
                case 11:
                    binding.tvHouseStatus.setText("驳回(经管)");
                    break;
                case 12:
                    binding.tvHouseStatus.setText("未知");
                    break;
                default:
                    binding.tvHouseStatus.setText("暂无");
                    break;
            }
        }

        //图片
        if (data.containsKey("imgList")) {
            final ArrayList<Map<String, Object>> mImgList = JSON.parseObject(data.getJSONArray("imgList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
            });
            final ArrayList<String> imageList = new ArrayList<>();
            final ArrayList<String> nameList = new ArrayList<>();
            for (Map<String, Object> map : mImgList) {
                imageList.add(ApiConfig.MAGEHEADER_URL() + map.get("imgUrl").toString());
                nameList.add(String.valueOf(map.get("name")));
            }
            if (!TextUtils.isEmpty(VRImgUrl)) {
                //有vr
                imageList.add(0, VRImgUrl);
            }
            if (imageList.size() == 0) {
                imageList.add("http://");
            }else{
                binding.idImgIndex.setVisibility(View.VISIBLE);
                binding.idImgIndex.setText( "1/" + imageList.size());
            }
            binding.idHouseAlbum.setImagesUrl(imageList);
            if (mImgList.size()>0){
                Map<String, Object> map = mImgList.get(0);
                String name = String.valueOf(map.get("name"));
                String format = String.format(Locale.CHINESE, "%d/%d", 1, imageList.size());
                binding.idHouseName.setText(name);
                binding.idHouseName.setVisibility(View.VISIBLE);
                binding.idImgIndex.setText(format);
            }

            binding.idHouseAlbum.setOnPageChangeListener(position -> {
                int pos = position;
                if (mImgList.size()>pos && pos!=-1){
                    Map<String, Object> map = mImgList.get(pos);
                    String name = String.valueOf(map.get("name"));
                    String format = String.format(Locale.CHINESE, "%d/%d", (1 + position), imageList.size());
                    binding.idHouseName.setText(name);
                    binding.idHouseName.setVisibility(View.VISIBLE);
                    binding.idImgIndex.setText(format);
                }
            });
            binding.idHouseAlbum.setOnItemClickListener(position -> {
                if (!TextUtils.isEmpty(finalVRImgUrl) && position == 0) {

                }else {
                    ArrayList<String> imgList = new ArrayList<>();
                    ArrayList<String> naList = new ArrayList<>();
                    if (!TextUtils.isEmpty(finalVRImgUrl)) {
                        imgList.addAll(imageList.subList(1, imageList.size()));
                        naList.addAll(nameList.subList(1,nameList.size()));
                        position--;
                    } else {
                        imgList.addAll(imageList);
                        naList.addAll(nameList);
                    }
                    Intent intent = new Intent(getActivity(), ImageViewPagerActivity.class);
                    intent.putStringArrayListExtra("imgs", imgList);
                    intent.putStringArrayListExtra("names", naList);
                    intent.putExtra("position",position+1);
                    intent.putExtra("check","picture");
                    startActivity(intent);
                }
            });
        }
        //居室
        if (data.containsKey("houseType"))
            binding.jushi.setText(data.get("houseType").toString());
        //楼层
        if (data.containsKey("floorType")) {
            if (data.get("floorType").toString().equals("1")) {
                binding.louceng.setText("低楼层");
            } else if (data.get("floorType").toString().equals("2")) {
                binding.louceng.setText("中楼层");
            } else if (data.get("floorType").toString().equals("3")) {
                binding.louceng.setText("高楼层");
            }
        }
        if( data.containsKey("allFloor") ){
            binding.floorCount.setText(data.getString("allFloor").concat("层到顶"));
        }
        //面积
        if (data.containsKey("square"))
            binding.mianji.setText(data.get("square") + "㎡");
        //朝向
        if (data.containsKey("face"))
            binding.chaoxiang.setText(data.get("face").toString());
        //带看量
        binding.tvVisitCount.setText("近7天" + data.get("weekViewCount") + "条,共" + data.get("viewCount") + "条");
        //委托时间 entrustTime
        if (data.containsKey("entrustTime"))
            binding.tvDelegateTime.setText(DateUtil.getTime(data.get("entrustTime").toString(), "yyyy-MM-dd HH:mm"));
        //编号
        rCode = data.get("rscode").toString();
        binding.tvSerialNumber.setText(data.get("rscode").toString());
        //钥匙信息
        if (data.containsKey("key"))
            binding.tvDoorKey.setText(data.get("key").toString());
        //委托来源
        if (data.containsKey("entrustSource"))
            binding.tvDelegateSource.setText(data.get("entrustSource").toString());
        //委托记录条数
        if (data.containsKey("entrustCount"))
            binding.tvDelegateHistory.setText(data.get("entrustCount").toString());
        //最新调价时间
        if (TextUtils.isEmpty(data.get("adjustTime").toString())) {
            binding.rlAdjustLayout.setVisibility(View.GONE);
        } else {
            binding.rlAdjustLayout.setVisibility(View.VISIBLE);
            if (data.containsKey("adjustTime"))
                binding.tvAdjustTime.setText(DateUtil.getTime(data.get("adjustTime").toString(), "yyyy-MM-dd HH:mm"));
            //最新调价
            double p = Double.parseDouble(data.get("adjustPriceEnd").toString()) - Double.parseDouble(data.get("adjustPrice").toString());
            String str = "";
            java.text.DecimalFormat myformat = new java.text.DecimalFormat("0.00");
            if (type.equals("shs")) {
                //出售
                if (p > 0) {
                    //涨价
                    str = str.concat(myformat.format(Double.valueOf(data.get("adjustPriceEnd").toString()))).concat("万").concat("(<font color=\"#FF0000\">+").concat(myformat.format(p)).concat("</font>万)");
                } else {
                    str = str.concat(myformat.format(Double.valueOf(data.get("adjustPriceEnd").toString()))).concat("万").concat("(<font color=\"#0B9800\">").concat(myformat.format(p)).concat("</font>万)");
                }
            } else {
                if (p > 0) {
                    //涨价
                    str = str.concat(myformat.format(Double.valueOf(data.get("adjustPriceEnd").toString()))).concat("元").concat("(<font color=\"#FF0000\">+").concat(myformat.format(p)).concat("</font>元)");
                } else {
                    str = str.concat(myformat.format(Double.valueOf(data.get("adjustPriceEnd").toString()))).concat("元").concat("(<font color=\"#0B9800\">").concat(myformat.format(p)).concat("</font>元)");
                }
            }

            binding.tvAdjustPrice.setText(Html.fromHtml(str));

            //调价人和部门
            if (data.containsKey("adjustName"))
                binding.tvAdjustAuthor.setText(data.get("adjustName") + "      " + data.get("adjustDept"));
        }
        //角色人信息
        if (data.containsKey("responsibleList")) {
            dataList = JSON.parseObject(data.getJSONArray("responsibleList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
            });
            if (dataList.size() > 0){
                roleAdapter.setData(dataList);
                binding.yfListview.setOnItemClickListener((parent, view, position, id) -> {
                    phoneNO = dataList.get(position).get("tel").toString();
                    CallUtils.CallTel(getContext(),phoneNO);
                });
            }else {
                binding.peopleInfo.setVisibility(View.GONE);
                binding.line1.setVisibility(View.GONE);
                binding.line2.setVisibility(View.GONE);
                binding.line3.setVisibility(View.GONE);
                binding.yfListview.setVisibility(View.GONE);
            }

        }
        binding.vScroll.smoothScrollTo(0,0);
        JSONObject object = data;
        object.put("type",type);
        EventBus.getDefault().post(object, "TAG_HOUSE_DATA");
    }

}
